package com.gillion.grape.fros.ui;

import net.java.amateras.uml.DiagramSerializer;
import net.java.amateras.uml.classdiagram.model.AttributeModel;
import net.java.amateras.uml.model.RootModel;
import net.java.amateras.xstream.XStreamSerializer;

import org.eclipse.core.resources.IFile;
import org.eclipse.ui.IFileEditorInput;

import com.gillion.grape.core.Logger;
import com.gillion.grape.meta.Column;
import com.gillion.grape.meta.Table;

/**
 * 实体模型转ER模型工具函数
 * 
 * @author meichenhui
 * @since 2011-8-23
 * 
 */
public class Entity2ERUtils {
	public static final String[] FILTERED_COLUMNS = { "createdByUser", "createdOffice", "createdDtmLoc", "createdTimeZone", "updatedByUser", "updatedOffice", "updatedDtmLoc",
			"updatedTimeZone", "recordVersion", "principalGroupCode" };

	/**
	 * 属性转换为ER模型中的物理名称 whCodeIDA --> WH_CODE_I_D_A
	 * 
	 * @param logicalName
	 * @return
	 * 
	 * @author meichenhui
	 * @since 2011-8-23
	 * 
	 */
	public static String logicalName2PhysicalName(String logicalName) {
		// 将首字母转换为大写 whCodeIdC --> WhCodeIdC
		String trueLogicalName = logicalName.replaceAll("^[a-zA-Z]", logicalName.substring(0, 1).toUpperCase());
		// 拆分字符串 WhCodeIdC --> [,h,ode,d]
		char[] chars = trueLogicalName.toCharArray();
		StringBuilder result = new StringBuilder();
		for (Character aChar : chars) {
			if(Character.isUpperCase(aChar)){
				result.append('_');
			}
			result.append(Character.toUpperCase(aChar));
		}
		return result.substring(1);
	}

	/**
	 * 属性转换为ER模型中的物理名称(一对多)
	 * 
	 * @param logicalName
	 * @return
	 */
	public static String logicalName2PhysicalName4One2Many(String logicalName) {
		String temp = logicalName2PhysicalName(logicalName);
		return temp.substring(0, temp.length()-1) + "_ID";
	}

	/**
	 * 属性转换为ER的数据类型 String --> varchar(n)
	 * 
	 * @param attribute
	 * @return
	 * 
	 * @author meichenhui
	 * @since 2011-8-23
	 * 
	 */
	public static String attributeType2ERType(Column attribute) {
		if ("String".equals(attribute.getType())) {
			return "varchar(n)";
		}
		return attribute.getType();
	}

	/**
	 * 判断属性是否为主键
	 * 
	 * @param column
	 * @return
	 * 
	 * @author meichenhui
	 * @since 2011-8-24
	 * 
	 */
	public static boolean isPrimaryKey(Column column) {
		return false;
	}

	/**
	 * 创建主键
	 * 
	 * @param table
	 * @return
	 * 
	 * @author meichenhui
	 * @since 2011-8-24
	 * 
	 */
	public static Column genPrimaryKey(Table table) {
		String primaryKeyName = table.getName() + "Id";
		Column primaryKey = new Column(primaryKeyName, "String", "60");
		primaryKey.setPrimaryKey(true);
		return primaryKey;
	}

	/**
	 * 从实体名生成主键属性
	 * 
	 * @param entityName
	 * @return
	 * 
	 * @author meichenhui
	 * @since 2011-9-6
	 * 
	 */
	public static String genPrimaryKeyProperty(String entityName) {
		return Entity2ERUtils.lowerTitle(entityName) + "Id";
	}

	/**
	 * 拆分属性类型描述为属性类型+属性长度 String(60) 拆分为 类型String 长度60 Number(10,5) --> "Number" "10,5" String(50) --> "String" "50"
	 * 
	 * @param originalType
	 * @return
	 * 
	 * @author meichenhui
	 * @since 2011-8-23
	 * 
	 */
	public static String[] splitAttributeTypeLength(String originalType) {
		if (!originalType.contains(")")) {
			return new String[] { originalType };
		}
		// System.out.println(originalType);
		String[] typeLength = originalType.split("\\(");
		typeLength[1] = typeLength[1].substring(0, typeLength[1].length() - 1);
		// System.out.println(typeLength[0] + typeLength[1]);
		return typeLength;
	}

	/**
	 * 拆分属性类型描述为属性类型+属性长度 String(60) 拆分为 类型String 长度60 Number(10,5) --> "BigDecimal" "10,5" String(50) --> "String" "50"
	 * 
	 * @param originalType
	 * @return
	 * 
	 * @author meichenhui
	 * @since 2011-8-23
	 * 
	 */
	public static String[] splitAttributeTypeLength(String originalType, boolean transform2javaType) {
		String[] splited = splitAttributeTypeLength(originalType);
		if (transform2javaType) {
			String modelType = splited[0];
			String length = "0";
			if (splited.length > 1) {
				length = splited[1];
			}
			if ("number".equals(modelType.toLowerCase())) {
				if (length.contains(",")) {
					splited[0] = "BigDecimal";
				} else if ("1".equals(length)) {
					splited[0] = "Boolean";
				} else {
					splited[0] = "Integer";
				}
			}
			if ("char".equals(modelType.toLowerCase())) {
				splited[0] = "Char";
				return splited;
			}
		}
		return splited;
	}

	/**
	 * 反序列化UML模型文件
	 * 
	 * @param umlModelInput
	 * @return
	 * 
	 * @author meichenhui
	 * @since 2011-8-23
	 * 
	 */
	public static RootModel deserializUMLDiagram(IFileEditorInput umlModelInput) {
		RootModel diagramObject = new RootModel();
		try { // 将UML图形反序列化为图形对象
			diagramObject = DiagramSerializer.deserialize(umlModelInput.getFile().getContents());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return diagramObject;
	}

	/**
	 * 反序列化UML模型文件
	 * 
	 * @param umlModelInput
	 * @return
	 * 
	 * @author meichenhui
	 * @since 2011-8-23
	 * 
	 */
	public static RootModel deserializUMLDiagram(IFile umlModelFile) {
		RootModel diagramObject = new RootModel();
		try { // 将UML图形反序列化为图形对象
			diagramObject = DiagramSerializer.deserialize(umlModelFile.getContents());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return diagramObject;
	}

	/**
	 * 得到UML模型的类名
	 * 
	 * @param modelName
	 * @return
	 * 
	 * @author meichenhui
	 * @since 2011-8-25
	 * 
	 */
	public static String getClassSimpleName(String modelName) {
		String simpleName = modelName;
		if (simpleName != null) {
			int lastDotPosition = simpleName.lastIndexOf('.');
			if (lastDotPosition != -1) {
				simpleName = simpleName.substring(lastDotPosition + 1);
			}
		}
		return simpleName;
	}

	/**
	 * 首字母小写
	 * 
	 * @param str
	 * @return
	 * 
	 * @author meichenhui
	 * @since 2011-8-25
	 * 
	 */
	public static String lowerTitle(String str) {
		if (str == null || str.length() == 0){
			return new String();
		}
		String title = str.substring(0, 1).toLowerCase();
		return title + str.substring(1);
	}


	/**
	 * 将字符串str的首字母转换为大写
	 * 
	 * @param str
	 * @return
	 */
	public static String upperTitle(String str) {
		return str.substring(0, 1).toUpperCase() + str.substring(1);
	}

	public static String umlType2JavaType(AttributeModel umlType) {
		// if ("number".equals(umlType.getType().toLowerCase())){
		// umlType.get
		// }
		return "String";
	}

	public static String javaType2OracleType(String javaType) {
		if ("String".equals(javaType)) {
			return "VARCHAR2";
		}
		if ("Boolean".equals(javaType)) {
			return "NUMBER(1)";
		}
		if ("BigDecimal".equals(javaType)) {
			return "NUMBER(10,5)";
		}
		if ("Integer".equals(javaType)) {
			return "NUMBER(10)";
		}
		if ("Char".equals(javaType)) {
			return "CHAR(1)";
		}
		return "String";
	}

	/**
	 * 测试
	 * 
	 * @param args
	 * 
	 * @author meichenhui
	 * @since 2011-8-23
	 * 
	 */
	public static void main(String[] args) {
		String phyName = logicalName2PhysicalName("WhCodeIdCD");
		System.out.println(phyName);
	}

}
